package com.lhz.framework.security.limiter;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.util.List;

/**
 * @Author: LiHuaZhi
 * @Date: 2021/7/18 18:46
 * @Description:
 **/
@Configuration
@Slf4j
public class RedisLuaConfig {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * @param keyList redis得Lua脚本中的key列表，我们把参数放在这里面传递
     * @return result 返回 1表示，正常，0表示限制访问
     */
    public String runLuaScript(List<String> keyList) {
        DefaultRedisScript<String> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/rateLimit.lua")));
        redisScript.setResultType(String.class);
        try {
            return stringRedisTemplate.execute(redisScript, keyList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "0";
        }
    }
}
